import useAsyncLoad from '@/hooks/useAsyncLoad';
import { AssignTaskContext } from '.';
import { Empty, message } from 'antd';
import React from 'react';
import orgCtrl from '@/ts/controller';
import { FieldModel, FormEditData, InstanceDataModel } from '@/ts/base/model';
import WorkForm from '@/executor/tools/workForm';
import { formatDate } from '@/utils';
import { IAssignTask } from '@/ts/core/work/assign';
import LoadingView from '@/components/Common/Loading';

export interface IProps {
  assignTask: IAssignTask;
}

/** 纯数据（不含流程实例查询） */
export function AssignDataView({ assignTask }: IProps) {
  const belongId = assignTask.metadata.belongId;

  const [loaded, combine] = useAsyncLoad(async () => {
    const work = await assignTask.loadWork();
    if (!work) {
      return;
    }
    const node = await work.loadNode();
    if (!node) {
      return;
    }

    let data: Dictionary<FormEditData[]> = {};

    for (const [formId, thingId] of Object.entries(assignTask.metadata.thingId || {})) {
      data[formId] ||= [];

      const form = work.forms.find((f) => f.id == formId);
      if (!form) {
        console.warn(`报表 ${formId} 不存在`);
        continue;
      }

      const things = await form.thingColl.loadSpace({
        options: {
          match: {
            id: {
              _in_: thingId,
            },
          },
        },
      });
      if (things.length != thingId.length) {
        message.warning(`找不到报表 ${form.name} 的数据`);
      }

      for (const d of things) {
        for (const attr of form.attributes) {
          d[attr.id] = d[`R${attr.propId}`];
          delete d[`R${attr.propId}`];
        }
      }

      data[formId].push({
        afterTempId: '',
        beforeTempId: '',
        before: [],
        after: things,
        rules: [],
        formName: form.name,
        creator: work.directory.userId,
        createTime: formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss.S'),
        nodeId: node.id,
      });
    }

    let instance: InstanceDataModel = {
      data,
      fields: work.forms.reduce<Dictionary<FieldModel[]>>((a, f) => {
        a[f.id] = f.fields;
        return a;
      }, {}),
      primary: {},
      node,
      rules: [],
      assignTask: assignTask.metadata,
    };

    const belong = orgCtrl.user.companys.find((a) => a.id == belongId) || orgCtrl.user;
    return { data: instance, belong };
  });

  if (!loaded) {
    return (
      <div className="loading-page">
        <LoadingView text="信息加载中..." />
      </div>
    );
  }
  if (!combine) {
    return (
      <div style={{ width: '100%', height: '100%' }}>
        <Empty description="找不到关联办事" />
      </div>
    );
  }

  return (
    <AssignTaskContext.Provider value={assignTask}>
      <div>
        {Object.keys(combine.data.data).length > 0 ? (
          <WorkForm
            allowEdit={false}
            belong={combine.belong}
            nodeId={combine.data.node.id}
            data={combine.data}
          />
        ) : (
          <Empty style={{ marginTop: '20%' }}>
            <div>任务已过期</div>
            <div>暂无自动补全数据</div>
          </Empty>
        )}
      </div>
    </AssignTaskContext.Provider>
  );
}
